package org.lyd.spring.restful.service.impl;

import org.lyd.spring.restful.bean.Employee;
import org.lyd.spring.restful.comom.BizException;
import org.lyd.spring.restful.comom.ResultCodeEnum;
import org.lyd.spring.restful.dao.EmployeeDao;
import org.lyd.spring.restful.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author:lyd
 **/
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDao employeeDao;

    @Override
    public Employee get(Integer id) {
        return employeeDao.get(id);
    }

    @Override
    public void addEmployee(Employee employee) {
        employeeDao.addEmployee(employee);
    }

    @Override
    public void updateEmployee(Employee employee) {
        //Controller层传来的Employee部分属性可能为null值，需要进行判断
        //1、从数据库中获取到该id对应的Employee对象
        //2、如果传过来的属性为null值就用数据库中默认值
        Integer id = employee.getId();
        if (employee.getId() == null) {
            //抛出业务异常
            throw new BizException(ResultCodeEnum.BUSINISS_ERROR);
        }
        Employee employeeDB = employeeDao.get(id);
        if (StringUtils.hasText(employee.getName())) {
            employeeDB.setName(employee.getName());
        }
        if (employee.getAge() != null) {
            employeeDB.setAge(employee.getAge());
        }
        if (StringUtils.hasText(employee.getEmail())) {
            employeeDB.setEmail(employee.getEmail());
        }
        if (StringUtils.hasText(employee.getGender())) {
            employeeDB.setGender(employee.getGender());
        }
        if (StringUtils.hasText(employee.getAddress())) {
            employeeDB.setAddress(employee.getAddress());
        }
        if (employee.getSalary() != null) {
            employeeDB.setSalary(employee.getSalary());
        }

        employeeDao.updateEmployee(employeeDB);
    }

    @Override
    public void deleteEmployee(Integer id) {
        employeeDao.deleteEmployee(id);
    }

    @Override
    public List<Employee> getList() {
        return employeeDao.getList();
    }
}
